package com.suning.sawp.web.controller;

import java.security.Principal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.intf.bind.BindDeviceService;
import com.suning.sawp.intf.bind.dto.ApplyAndBindRtnDto;
import com.suning.sawp.intf.bind.dto.BindRecordDto;
import com.suning.sawp.intf.bind.dto.BindUnlockApplyDto;
import com.suning.sawp.intf.customer.CustRemarkService;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.sys.SystemService;
import com.suning.sawp.service.util.AESUtils;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 设备绑定controller
 * 
 * @author 17061157
 * @see [相关类/方法]
 * @since 
 */
@Controller
@RequestMapping("/bindDevice")
public class BindDeviceController extends DjBaseController{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	CustRemarkService custRemarkService;
	
	@Autowired
	BindDeviceService bindDeviceService;
	
	/**
     * 
     * 功能描述: 查询申请解锁信息<br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
	@RequestMapping("/validAlreadyApplyUnlock.do")
	public MyGsonView validAlreadyApplyUnlock(Principal principal){
		// 获取当前用户id，即工号
		String staffId = principal.getName();
		ReturnMsg<ApplyAndBindRtnDto> ret = new ReturnMsg<ApplyAndBindRtnDto>();
		
        try{
        	ApplyAndBindRtnDto dto = new ApplyAndBindRtnDto();
        	// 查询解锁申请信息
        	BindUnlockApplyDto applyInfo = bindDeviceService.queryUnlockApplyInfo(staffId);
        	if (applyInfo != null) {
        		dto.setApplyDevice(applyInfo.getApplyDevice());
        		dto.setApplyReason(applyInfo.getApplyReason());
        		dto.setApplyTime(applyInfo.getApplyTime());
        	} else {
        		// 查询驳回信息
        		ApplyAndBindRtnDto rejectDto = bindDeviceService.queryRejectInfo(staffId);
        		if (rejectDto != null) {
        			dto = rejectDto;
        		}
        	}
        	// 查询最近三次绑定信息
        	List<BindRecordDto> bindInfos = bindDeviceService.queryLatestThreeBindInfo(staffId);
        	dto.setList(bindInfos);
        	
        	ret.setData(dto);
        } catch (Exception e){
        	LOGGER.error(String.format("BindDeviceController validAlreadyApplyUnlock param(staffId:%s)", staffId), e);
        	ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
        }
        
		return setGsonView(ret);
	}
	
	/**
	 * 
	 * 功能描述: 发起解锁申请<br>
	 * 〈功能详细描述〉
	 *
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	@RequestMapping("/applyUnlock.do")
	public MyGsonView applyUnlock(Principal principal, HttpServletRequest request, 
			String applyReason, String djDeviceId, String deviceName){
		ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
		// 获取当前用户id，即工号
		String staffId = principal.getName();
		
		String ip = getUserIp(request);
		
		// 解密客户端传过来的加密设备ID
        String deviceId = AESUtils.decodeAndDecrypt(djDeviceId, ConfigConstants.AES_KEY);
        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(deviceName)) {
        	LOGGER.error("BindDeviceController applyUnlock device Param is empty,deviceId:{}, deviceName:{}", deviceId, deviceName);
            ret.setError(ErrorCodeConstants.ERR_0024, ErrorCodeConstants.ERR_MAP);
            return setGsonView(ret);
        }
		
		try{
			ret = bindDeviceService.unlockApply(staffId, deviceId, deviceName, applyReason, ip);
		} catch (Exception e){
			LOGGER.error(String.format("BindDeviceController applyUnlock param(staffId:%s,deviceId:%s)", staffId, deviceId), e);
			ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
		}
		
		return setGsonView(ret);
	}

	/**
     * 
     * 功能描述: 取请求IP<br>
     * 〈功能详细描述〉
     *
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getUserIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (hasDeepIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (hasDeepIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (hasDeepIp(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (hasDeepIp(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (hasDeepIp(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * 
     * 功能描述: 判断IP是否OK<br>
     * 〈功能详细描述〉
     *
     * @param ip
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean hasDeepIp(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }
}
